今天我们来看一下 powershell 中的循环。在 powershell 有两种循环,一种 for(foreach) 循环,用于遍历;另一个是 witch 用于条件循环,只有满足特定的(循环)条件,才会进行循环。
今天我们就来看一下 for 循环。
语法格式:
for (<Initialization>; <Condition or Test_expression>; <Repeat>)
{
doing
}
示例:输出 0 到 9 的数字。
for ($i=0; $i -lt 10; $i++)
{
Write-Host $i
}
运行结果:
0
1
2
3
4
5
6
7
8
9
如果 for 循环的对象是一个数组,如:
$colors = "Red","Orange","Green","White","Blue","Indigo","black","Violet"
for ($i=0; $i -lt $colors.Length; $i++)
{
Write-Host $colors[$i]
}
运行结果:
Red
Orange
Green
White
Blue
Indigo
black
Violet
在 powershell 中,还有另一种 “for 循环”,就是 foreach:
$colors = "Red","Orange","Green","White","Blue","Indigo","black","Violet"
foreach ( $i in $colors )
{
Write-Host $i
}
运行结果:
Red
Orange
Green
White
Blue
Indigo
black
Violet